package com.nuoyuan.wx.admin.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuoyuan.wx.common.constant.BookTypeEnum;
import com.nuoyuan.wx.common.controller.BaseController;
import com.nuoyuan.wx.common.utils.DateUtil;
import com.nuoyuan.wx.common.utils.ExcelUtils;
import com.nuoyuan.wx.common.utils.GsonUtil;
import com.nuoyuan.wx.common.utils.SmsUtil;
import com.nuoyuan.wx.dao.mapper.BookMapper;
import com.nuoyuan.wx.dao.po.BookPo;
import com.nuoyuan.wx.dao.po.UserPo;
import com.nuoyuan.wx.service.helper.BookBeanHelper;
import com.nuoyuan.wx.vo.BookQueryVo;
import com.nuoyuan.wx.vo.PageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Package com.nuoyuan.wx.admin.controller
 * @ClassName BookController
 * @Description TODO
 * @Author linus
 * @Date 2020-02-13 14:21
 * @Version 1.0
 **/
@RestController("AdminBookController")
public class BookController extends BaseController {
    public static final Logger log = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookMapper bookMapper;
    /**
     * 列表
     * @param query
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/books", method = RequestMethod.GET)
    @ResponseBody
    public String list(BookQueryVo query, HttpServletRequest request, HttpServletResponse response) {

        try {
            Wrapper<BookPo> wrapper = new QueryWrapper<>();
            if(BookTypeEnum.valueOf(query.getBookType()).equals(BookTypeEnum.BOOKING)) {
                ((QueryWrapper<BookPo>) wrapper).eq("book_type", query.getBookType()).eq("is_deleted", 0).eq("product_id", query.getProductId()).orderByDesc("book_id");
            }else {
                ((QueryWrapper<BookPo>) wrapper).eq("book_type", query.getBookType()).eq("is_deleted", 0).orderByDesc("book_id");
            }

            IPage p = new Page();
            p.setCurrent(query.getPageNo());
            p.setSize(query.getPageSize());
            IPage<BookPo> pages = bookMapper.selectPage(p, wrapper);

            if(pages == null || CollectionUtils.isEmpty(pages.getRecords())) {
                PageVo emptyP = new PageVo<>();
                emptyP.setItems(new ArrayList());
                return GsonUtil.toJson(emptyP);
            }

            PageVo page = new PageVo();
            page.setCount(pages.getTotal());
            page.setItems(BookBeanHelper.toVos(pages.getRecords()));

            return GsonUtil.toJson(page);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }

    }



    @RequestMapping(value = "/admin/book/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@RequestBody BookQueryVo update, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Long> bookIds = update.getBookIds();
            for (Long bookId : bookIds) {
                Wrapper<BookPo> updateWrapper = new UpdateWrapper<>();
                ((UpdateWrapper<BookPo>) updateWrapper).eq("book_id", bookId);
                BookPo po = new BookPo();
                po.setIsDeleted(true);
                bookMapper.update(po, updateWrapper);
            }
            return this.buildSimpleSuccResp();
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
    }


    /**
     * 更新
     * @param update
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/book/sms", method = RequestMethod.POST)
    @ResponseBody
    public String sms(@RequestBody BookQueryVo update, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Long> bookIds = update.getBookIds();
            String current = DateUtil.formatTimestamp(DateUtil.getCurrentTimestamp(), DateUtil.FMT_DATE_YYYYMMDD_HHMMSS);
            List<String> phones = new ArrayList<>();
            for (Long bookId : bookIds) {
                Wrapper<BookPo> queryWrapper = new QueryWrapper<>();
                ((QueryWrapper<BookPo>) queryWrapper).eq("book_id", bookId);
                BookPo book = bookMapper.selectOne(queryWrapper);
                phones.add(book.getPhone());

                Wrapper<BookPo> updateWrapper = new UpdateWrapper<>();
                ((UpdateWrapper<BookPo>) updateWrapper).eq("book_id", bookId);
                book.setIsSms(true);
                bookMapper.update(book, updateWrapper);
            }
            String joinPhones = phones.stream().distinct().collect(Collectors.joining(","));
            SmsUtil.sendSms(joinPhones, update.getContent(), current);

            return this.buildSimpleSuccResp();
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
    }


    /**
     * 产品管理页导出
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/admin/book/export")
    public void export(@RequestBody BookQueryVo query, HttpServletResponse response) throws Exception {
        try {
            Wrapper<BookPo> queryWrapper = new QueryWrapper<>();
            ((QueryWrapper<BookPo>) queryWrapper).eq("book_type", BookTypeEnum.valueOf(query.getBookType()).name());
            List<BookPo> books = bookMapper.selectList(queryWrapper);
            if(!CollectionUtils.isEmpty(books)) {
                String title = BookTypeEnum.BOOKING.equals(BookTypeEnum.valueOf(query.getBookType())) ? "预约列表" : "转让列表";

                List<String> headers = new ArrayList<>();
                headers.add("编号");
                headers.add("产品名称");
                headers.add("产品编号");
                headers.add("姓名");
                headers.add("身份证号");
                headers.add("手机号");
                headers.add("预约金额");
                headers.add("时间日期");
                headers.add("通知状态");

                List<List<String>> datas = new ArrayList<>();
                for(BookPo po : books) {
                    List<String> rowData = new ArrayList<>();
                    rowData.add(po.getBookId().toString());
                    rowData.add(po.getProductName());
                    rowData.add(po.getProductNo());
                    rowData.add(po.getRealName());
                    rowData.add(po.getIdNo());
                    rowData.add(po.getPhone());
                    rowData.add(po.getAppointmentAmount().toString());
                    rowData.add(DateUtil.formatDate(po.getCreateTime(), DateUtil.FMT_DATE_YYYYMMDD_HHMMSS));
                    rowData.add(po.getIsSms() ? "已短信通知" : "未短信通知");

                    datas.add(rowData);
                }

                ExcelUtils.exportExcel(response, title, "", headers, datas);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}
